package com.sephiron.clocksynchronizer;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONTokener;

import android.content.Context;
import android.util.Log;

public class CctvJSONSerializer {
	private static final String TAG = "CctvJSONSerializer";
	private Context mContext;
	private String mFilename;

	public CctvJSONSerializer(Context c, String f) {
		mContext = c;
		mFilename = f;
	}

	public void saveCctvs(ArrayList<Cctv> cctvs) throws JSONException,
			IOException {
		JSONArray array = new JSONArray();
		for (Cctv c : cctvs)
			array.put(c.toJSON());

		Writer writer = null;
		try {
			OutputStream out = mContext.openFileOutput(mFilename,
					Context.MODE_PRIVATE);
			writer = new OutputStreamWriter(out);
			Log.d(TAG,"json array written as : " + array.toString());
			writer.write(array.toString());
		} finally {
			if (writer != null)
				writer.close();
		}
	}

	public ArrayList<Cctv> loadCctvs() throws IOException, JSONException {
		ArrayList<Cctv> cctvs = new ArrayList<Cctv>();
		BufferedReader reader = null;
		try {
			InputStream in = mContext.openFileInput(mFilename);
			reader = new BufferedReader(new InputStreamReader(in));
			StringBuilder jsonString = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				jsonString.append(line);
			}

			JSONArray array = (JSONArray) new JSONTokener(jsonString.toString())
					.nextValue();

			for (int i = 0; i < array.length(); i++) {
				Log.d(TAG,"json array written as : " + array.getJSONObject(i).toString());
				cctvs.add(new Cctv(array.getJSONObject(i)));
			}

		} catch (FileNotFoundException e) {
		} finally {
			if (reader != null) {
				reader.close();
			}
		}
		return cctvs;
	}
}
